package com.shqcjd.yunweiyanoperator.ui.activity.remote;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Chronometer;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.orhanobut.logger.Logger;
import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.app.MyApp;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxObserver;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.ui.base.BaseActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.util.DateUtil;
import com.shqcjd.yunweiyanoperator.util.PrefUtils;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.agora.AgoraAPIOnlySignal;
import io.agora.rtc.Constants;
import io.agora.rtc.RtcEngine;
import io.agora.rtc.video.VideoCanvas;
import io.agora.rtc.video.VideoEncoderConfiguration;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 录制视频
 */
public class VideotapeActivity extends BaseActivity implements MyApp.OnAgoraEngineInterface {
    @BindView(R.id.remote_video_view_container)
    FrameLayout container;
    @BindView(R.id.cb_call_mute_button)
    CheckBox cbCallMuteButton;
    @BindView(R.id.ll_mute_btn)
    LinearLayout llMuteBtn;
    @BindView(R.id.ll_file_btn)
    LinearLayout llFileBtn;
    @BindView(R.id.chronometer_layout)
    Chronometer chronometer_layout;
    @BindView(R.id.ll_hang_up_btn)
    LinearLayout llHangUpBtn;
    @BindView(R.id.rl_menu)
    RelativeLayout rlMenu;
    @BindView(R.id.rl_full_screen)
    RelativeLayout rlFullScreen;
    @BindView(R.id.rv_user_list)
    RecyclerView rv_user_list;
    @BindView(R.id.tv_msg_content)
    TextView tv_msg_content;
    private String channelID;
    private RtcEngine mRtcEngine;
    private Context mContext;
    private int userId;
    private String appCode;
    private String userName;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_push_video_call;
    }

    @Override
    public void initView() {
        mContext = this;
        llFileBtn.setVisibility(View.GONE);
        long curTimeLong = DateUtil.getCurTimeLong();
        channelID = "videotape@" + curTimeLong;

        userId = PrefUtils.getInt(mContext, PrefUtils.USER_ID, -1);
        appCode = PrefUtils.getString(mContext, PrefUtils.APPCODE, "");
        userName = PrefUtils.getString(mContext, PrefUtils.USER_NAME, "");

        checkPermissions();
    }

    /**
     * 控制静音
     */
    private CompoundButton.OnCheckedChangeListener oncheckChangeListerener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mRtcEngine.muteLocalAudioStream(isChecked);
        }
    };

    /**
     * 检测权限
     */
    private void checkPermissions() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            initAgoraEngineAndJoinChannel();
                        } else {
                            ToastUtils.showShort(mContext, "缺少远程指导必要权限");
                            finish();
                        }
                    }
                });
    }

    /**
     * 初始化远程指导
     */
    private void initAgoraEngineAndJoinChannel() {
        //初始化视频
        initializeAgoraEngine();     // 步骤1
        setupVideoProfile();         // 步骤2
        MyApp.the().setOnAgoraEngineInterface(this);
        setupLocalVideo();          // 步骤3
        joinChannel();               // 步骤4

    }

    private void initializeAgoraEngine() {
        mRtcEngine = MyApp.the().getmRtcEngine();
        if (mRtcEngine != null) {
            mRtcEngine.setLogFile("/sdcard/sdklog.txt");
        }
    }

    private void setupVideoProfile() {
        mRtcEngine.enableVideo();



        VideoEncoderConfiguration.VideoDimensions vd_1280x720 = VideoEncoderConfiguration.VD_1280x720;
        VideoEncoderConfiguration.FRAME_RATE frameRateFps15 = VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15;
        int standardBitrate = VideoEncoderConfiguration.STANDARD_BITRATE;
        VideoEncoderConfiguration.ORIENTATION_MODE orientationModeAdaptive = VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_LANDSCAPE;
        VideoEncoderConfiguration videoEncoderConfiguration = new VideoEncoderConfiguration(vd_1280x720, frameRateFps15, standardBitrate, orientationModeAdaptive);
        mRtcEngine.setVideoEncoderConfiguration(videoEncoderConfiguration);
    }

    private void setupLocalVideo() {
//        SurfaceView surfaceView = RtcEngine.CreateRendererView(getBaseContext());
////        surfaceView.setZOrderMediaOverlay(true);
//        container.addView(surfaceView);
//        //设置本地视频视频
//        mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, 0));
////        //镜像问题调用
////        mRtcEngine.setParameters("{\"che.video.localViewMirrorSetting\":\"disableMirror\"}");
//        mRtcEngine.startPreview();

        SurfaceView surfaceView = RtcEngine.CreateRendererView(getBaseContext());
        container.addView(surfaceView);
        mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, 0));
        container.setVisibility(View.VISIBLE);
        mRtcEngine.startPreview();
        //转换摄像头
        mRtcEngine.switchCamera();
    }

    private void joinChannel() {
        mRtcEngine.setChannelProfile(1);
        mRtcEngine.setClientRole(Constants.CLIENT_ROLE_BROADCASTER);
        mRtcEngine.enableWebSdkInteroperability(true);
        //关闭使用本地摄像头设备
//        mRtcEngine.enableLocalVideo(false);
        //加入视频频道
        Logger.i("加入房间号:" + channelID);
        int i1 = mRtcEngine.leaveChannel();
        int i = mRtcEngine.joinChannel(null, channelID, "Extra Optional Data", userId);// if you do not specify the uid, we will generate the uid for you
        Logger.i("加入频道码:" + i + "  离开频道:" + i1);
    }

    @OnClick({R.id.ll_mute_btn, R.id.ll_hang_up_btn, R.id.rl_full_screen})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_mute_btn://静音
                cbCallMuteButton.setChecked(!cbCallMuteButton.isChecked());
                break;
            case R.id.ll_hang_up_btn://挂断
                callOutHangup();
                break;
            case R.id.rl_full_screen://显示隐藏菜单
                rlMenu.setVisibility(rlMenu.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
                break;
        }
    }

    private void callOutHangup() {
        new MaterialDialog.Builder(mContext)
                .title("是否结束录像？")
                .positiveText("确认")
                .negativeText("取消")
                .onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {//确认
                            stopRecording();
                        } else if (which == DialogAction.NEGATIVE) {//取消
                            dialog.dismiss();
                        }

                    }
                }).show();
    }

    private void stopRecording(){
        Map<String, String> map = new HashMap<>();
        map.put("roomId", channelID);
        ApiService.stopRecording(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        showWaitingDialog("加载中");
                    }

                    @Override
                    public void _onNext(ResponseData retData) {
                        if (retData != null && retData.retCode == 10000) {
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                        hideWaitingDialog();
                        finish();
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                        finish();
                    }
                });
    }

    private void startRecording(){
//        String saveAgoraAppId = UIUtils.getSaveAgoraAppId(this);
        String saveAgoraAppId = getString(R.string.agora_app_id);//todo 记得改掉

        Map<String, String> map = new HashMap<>();
        map.put("videoUserId", userId+"");
        map.put("appId", saveAgoraAppId);
        map.put("guideStatus", "1");// 0:专家指导,1:录像 ,
        map.put("initiatorAppCode", appCode);
        map.put("initiatorUserId", userId+"");
        map.put("initiatorUserName", userName+"");
        map.put("roomId", channelID);
        ApiService.startRecording(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        showWaitingDialog("加载中");
                    }

                    @Override
                    public void _onNext(ResponseData retData) {
                        if (retData != null && retData.retCode == 10000) {

                        } else {
                            ToastUtils.showShort(mContext, "录制失败，请重新录制");
                            finish();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mRtcEngine != null) {
            mRtcEngine.switchCamera();
            mRtcEngine.stopPreview();
            mRtcEngine.leaveChannel();//离开频道
        }
//        mRtcEngine = null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onFirstRemoteVideoDecoded(int uid, int width, int height, int elapsed) {

    }

    @Override
    public void onUserJoined(int uid, int elapsed) {

    }

    @Override
    public void onUserOffline(int uid, int reason) {

    }

    @Override
    public void onUserMuteVideo(int uid, boolean muted) {

    }

    @Override
    public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                startRecording();
            }
        });

    }

    @Override
    public void onError(int err) {

    }
}
